package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.utils.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceimpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

   @Resource
    FileStorageService fileStorageService;

    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数校验
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        //判断用户是否登录
        if (user.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //文件名称设置
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String filename = multipartFile.getOriginalFilename();
        String sufix = filename.substring(filename.lastIndexOf("."));

        //上传图片
        String fileId = null;
        try {
            fileId = fileStorageService.store("material", uuid + sufix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        //封装数据保持到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        save(wmMaterial);
        //前端显示
        wmMaterial.setUrl(webSite + fileId);
        //返回结果
        return ResponseResult.okResult(wmMaterial);

    }

    @Resource
    WmUserMapper wmUserMapper;

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        //参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        //判断用户是否登录
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查看是否有对应的数据
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //根据用户id查询是否有该用户
        WmUser wmUser = wmUserMapper.selectById(user.getId());
        if (wmUser == null) {
            throw new CustomException(AppHttpCodeEnum.USER_INEXISTENCE);
        }

        //查看该图片是否被引用
        Integer count = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            throw new CustomException(AppHttpCodeEnum.STARUP_STATE, "改素材已被引用");
        }


        //删除图片
        this.remove(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, user.getId()).eq(WmMaterial::getId, id));
        //删除oss图片
        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser user = WmThreadLocalUtils.getUser();
        //判断用户是否登录
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //进行修改
        this.update(Wrappers.<WmMaterial>lambdaUpdate().eq(WmMaterial::getId, id).
                eq(WmMaterial::getUserId, user.getId()).set(WmMaterial::getIsCollection, type));

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //参数校验
        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页校验
        dto.checkParam();

        WmUser user = WmThreadLocalUtils.getUser();
        //判断用户是否登录
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //封装分页条件
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());

        //封装查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();

        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        queryWrapper.eq(WmMaterial::getUserId, user.getId());
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        //分页查询
        IPage<WmMaterial> resultPage = this.page(page, queryWrapper);


        PageResponseResult pageResponseResult = new PageResponseResult((int) resultPage.getCurrent(), (int) resultPage.getSize(), (int) resultPage.getTotal());
        //返回的结果，图片需要加上访问路径
        List<WmMaterial> records = resultPage.getRecords();
        for (WmMaterial wmMaterial : records) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }

        pageResponseResult.setData(resultPage.getRecords());

        return pageResponseResult;
    }


}

